<template>
  <div class="appointment-management">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ appointmentStats.total }}</div>
                <div class="stats-label">总预约</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon today">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ appointmentStats.today }}</div>
                <div class="stats-label">今日预约</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pending">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ appointmentStats.pending }}</div>
                <div class="stats-label">待确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon confirmed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ appointmentStats.confirmed }}</div>
                <div class="stats-label">已确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 日历视图 -->
    <el-card shadow="never" class="calendar-card">
      <template #header>
        <div class="calendar-header">
          <div>
            <el-icon><Calendar /></el-icon>
            预约日历
          </div>
          <div class="calendar-controls">
            <el-radio-group v-model="viewMode" @change="handleViewModeChange">
              <el-radio-button label="day">日视图</el-radio-button>
              <el-radio-button label="week">周视图</el-radio-button>
              <el-radio-button label="month">月视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      <div class="calendar-content">
        <el-calendar ref="calendarRef" v-model="selectedDate">
          <template #date-cell="{ data }">
            <div class="calendar-day">
              <div class="day-number">{{ data.day.split('-').slice(-1)[0] }}</div>
              <div class="appointment-count" v-if="getAppointmentCount(data.day) > 0">
                {{ getAppointmentCount(data.day) }}个预约
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
    </el-card>

    <!-- 搜索和操作栏 -->
    <el-card shadow="never" class="search-card">
      <div class="search-container">
        <div class="search-left">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索客户姓名、手机号"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="searchForm.status" placeholder="预约状态" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="待确认" value="PENDING" />
            <el-option label="已确认" value="CONFIRMED" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增预约
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 预约列表 -->
    <el-card shadow="never">
      <el-table
        :data="appointmentList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="客户信息" min-width="200">
          <template #default="{ row }">
            <div class="customer-info">
              <el-avatar :src="row.customerAvatar" :size="40">
                {{ row.customerName?.charAt(0) }}
              </el-avatar>
              <div class="customer-detail">
                <div class="customer-name">{{ row.customerName }}</div>
                <div class="customer-phone">{{ row.customerPhone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentDate" label="预约日期" width="120" />
        <el-table-column prop="appointmentTime" label="预约时间" width="120" />
        <el-table-column prop="serviceType" label="服务类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.serviceType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="服务地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="estimatedAmount" label="预估金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.estimatedAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              type="success" 
              link 
              @click="handleConfirm(row)"
              v-if="row.status === 'PENDING'"
            >
              <el-icon><Check /></el-icon>
              确认
            </el-button>
            <el-button 
              type="warning" 
              link 
              @click="handleReschedule(row)"
              v-if="['PENDING', 'CONFIRMED'].includes(row.status)"
            >
              <el-icon><Edit /></el-icon>
              改期
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleCancel(row)"
              v-if="['PENDING', 'CONFIRMED'].includes(row.status)"
            >
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="appointmentFormRef"
        :model="appointmentForm"
        :rules="appointmentFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="appointmentForm.customerName" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户手机" prop="customerPhone">
              <el-input v-model="appointmentForm.customerPhone" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约日期" prop="appointmentDate">
              <el-date-picker
                v-model="appointmentForm.appointmentDate"
                type="date"
                :disabled="isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="appointmentTime">
              <el-time-picker
                v-model="appointmentForm.appointmentTime"
                :disabled="isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务类型" prop="serviceType">
              <el-select v-model="appointmentForm.serviceType" :disabled="isView" style="width: 100%">
                <el-option label="上门取件" value="PICKUP" />
                <el-option label="送货上门" value="DELIVERY" />
                <el-option label="上门服务" value="HOME_SERVICE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估金额" prop="estimatedAmount">
              <el-input-number
                v-model="appointmentForm.estimatedAmount"
                :min="0"
                :disabled="isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务地址" prop="address">
          <el-input
            v-model="appointmentForm.address"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="appointmentForm.remark"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
      </el-form>
      <template #footer v-if="!isView">
        <el-button @click="detailVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const appointmentList = ref([])
const selectedAppointments = ref([])
const detailVisible = ref(false)
const isView = ref(false)
const dialogTitle = ref('')
const viewMode = ref('month')
const selectedDate = ref(new Date())

// 统计数据
const appointmentStats = ref({
  total: 156,
  today: 12,
  pending: 8,
  confirmed: 45
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 预约表单
const appointmentForm = reactive({
  id: null,
  customerName: '',
  customerPhone: '',
  appointmentDate: null,
  appointmentTime: null,
  serviceType: '',
  address: '',
  estimatedAmount: 0,
  remark: ''
})

// 表单验证规则
const appointmentFormRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  customerPhone: [
    { required: true, message: '请输入客户手机', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  serviceType: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入服务地址', trigger: 'blur' }
  ]
}

const appointmentFormRef = ref()

// 模拟数据
const mockAppointmentList = [
  {
    id: 1,
    customerName: '王女士',
    customerPhone: '13800138001',
    customerAvatar: '',
    appointmentDate: '2024-01-15',
    appointmentTime: '09:00',
    serviceType: '上门取件',
    address: '北京市朝阳区某某小区1号楼',
    estimatedAmount: 120,
    status: 'PENDING',
    createTime: '2024-01-14 10:30',
    remark: '请提前电话联系'
  },
  {
    id: 2,
    customerName: '李先生',
    customerPhone: '13800138002',
    customerAvatar: '',
    appointmentDate: '2024-01-15',
    appointmentTime: '14:00',
    serviceType: '送货上门',
    address: '北京市海淀区某某大厦A座',
    estimatedAmount: 180,
    status: 'CONFIRMED',
    createTime: '2024-01-13 15:20',
    remark: '工作日配送'
  }
]

// 获取预约列表
const fetchAppointmentList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    appointmentList.value = mockAppointmentList
    pagination.total = mockAppointmentList.length
  } catch (error) {
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 获取某日期的预约数量
const getAppointmentCount = (date) => {
  return appointmentList.value.filter(item => item.appointmentDate === date).length
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'COMPLETED': '',
    'CANCELLED': 'danger'
  }
  return types[status] || ''
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return texts[status] || '未知'
}

// 视图模式变化
const handleViewModeChange = (mode) => {
  ElMessage.info(`切换到${mode === 'day' ? '日' : mode === 'week' ? '周' : '月'}视图`)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchAppointmentList()
}

// 添加预约
const handleAdd = () => {
  isView.value = false
  dialogTitle.value = '新增预约'
  resetForm()
  detailVisible.value = true
}

// 查看预约
const handleView = (row) => {
  isView.value = true
  dialogTitle.value = '预约详情'
  fillForm(row)
  detailVisible.value = true
}

// 确认预约
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确认接受此预约吗？', '确认预约', {
      type: 'info'
    })
    ElMessage.success('预约已确认')
    fetchAppointmentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认失败')
    }
  }
}

// 改期
const handleReschedule = (row) => {
  ElMessage.info(`${row.customerName} - 改期功能开发中`)
}

// 取消预约
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消此预约吗？', '取消预约', {
      type: 'warning'
    })
    ElMessage.success('预约已取消')
    fetchAppointmentList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedAppointments.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchAppointmentList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchAppointmentList()
}

// 表单操作
const resetForm = () => {
  Object.assign(appointmentForm, {
    id: null,
    customerName: '',
    customerPhone: '',
    appointmentDate: null,
    appointmentTime: null,
    serviceType: '',
    address: '',
    estimatedAmount: 0,
    remark: ''
  })
}

const fillForm = (row) => {
  Object.assign(appointmentForm, row)
}

const handleSubmit = async () => {
  try {
    await appointmentFormRef.value.validate()
    submitLoading.value = true
    
    if (appointmentForm.id) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.success('添加成功')
    }
    
    detailVisible.value = false
    fetchAppointmentList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  appointmentFormRef.value?.resetFields()
}

// 页面加载
onMounted(() => {
  fetchAppointmentList()
})
</script>

<style scoped>
.appointment-management {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  overflow: hidden;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.today {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.pending {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stats-icon.confirmed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.calendar-card {
  margin-bottom: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-content {
  margin-top: 20px;
}

.calendar-day {
  height: 100%;
  padding: 4px;
}

.day-number {
  font-weight: bold;
  margin-bottom: 4px;
}

.appointment-count {
  font-size: 12px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 4px;
  border-radius: 4px;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-right {
  display: flex;
  gap: 12px;
}

.customer-info {
  display: flex;
  align-items: center;
}

.customer-detail {
  margin-left: 12px;
}

.customer-name {
  font-weight: 500;
  color: #303133;
}

.customer-phone {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.amount {
  font-weight: 500;
  color: #f56c6c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 120px;
}
</style> 